﻿using MySimpleMvc.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;

namespace MySimpleMvc.Handler
{
    /// <summary>
    /// MvcHandler 的摘要说明
    /// </summary>
    public class MvcHandler : IHttpHandler
    {
        // 路由表
        private IDictionary<string, string> routeData;

        // 所有控制器的类型集合
        private static IList<Type> alloctionControllerTypes;

        // 当前类第一次加载时调用静态构造函数
        static MvcHandler()
        {
            alloctionControllerTypes = new List<Type>();

            // 获得当前所有引用的程序集
            var assemblies = BuildManager.GetReferencedAssemblies();
            // 遍历所有的程序集
            foreach (Assembly assembly in assemblies)
            {
                // 获取当前程序集中所有的类型
                var allTypes = assembly.GetTypes();
                // 遍历所有的类型
                foreach (Type type in allTypes)
                {
                    // 如果当前类型满足条件
                    if (type.IsClass && !type.IsAbstract && type.IsPublic && typeof(IController).IsAssignableFrom(type))
                    {
                        // 将所有Controller加入集合
                        alloctionControllerTypes.Add(type);
                    }
                }
            }
        }

        public MvcHandler(IDictionary<string, string> routeData)
        {
            this.routeData = routeData;
        }

        public void ProcessRequest(HttpContext context)
        {
            var controllerName = routeData["{controller}"];

            if (string.IsNullOrEmpty(controllerName))
            {
                // 指定默认控制器
                controllerName = "home";
            }

            IController controller = null;
            // 通过反射的方式加载具体实例
            foreach (var controllerItem in alloctionControllerTypes)
            {
                if (controllerItem.Name.Equals(string.Format("{0}Controller", controllerName), StringComparison.InvariantCultureIgnoreCase))
                {
                    controller = Activator.CreateInstance(controllerItem) as IController;
                    break;
                }
            }

            var requestContext = new HttpContextWrapper()
            {
                Context = context,
                RouteData = routeData
            };
            controller.Execute(requestContext);
            Fuck();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void Fuck(params object[] aaa)
        {
            HttpContextWrapper a = new HttpContextWrapper();

            if (aaa != null)
            {

            }
        }
    }

    public class HttpContextWrapper
    {
        public HttpContext Context { get; set; }
        public IDictionary<string, string> RouteData { get; set; }
    }
}